package com.bdqn.controller;

import com.bdqn.pojo.User;
import com.bdqn.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * IndexController
 *
 * @author
 * @since
 */
@Controller
public class IndexController {

    @Resource
    private UserService userService;

    /**
     * 去到登录页面
     */
    @GetMapping("/login")
    public String toLogin() {
        return "login";
    }

    /**
     * 执行用户登录
     */
    @PostMapping("/doLogin")
    public String doLogin(Model model, HttpSession session, String usrName, String usrPassword) {
        // // 去数据库判断用户是否存在
        // User loginUser = userService.login(usrName, usrPassword);
        // // 用户密码不匹配
        // if (loginUser == null) {
        //     model.addAttribute("message", "账号或密码错误，请重新登录。");
        //     return "login";
        // }
        // // 把用户保存到Session中
        // session.setAttribute("loginUser", loginUser);
        // return "main";
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);//认证、登录
            //认证(登录)成功
            User sysUser = (User) subject.getPrincipal();
            session.setAttribute("loginUser", sysUser);
            return "main";//建议重定向，此处未重定向成功

        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("msg", "用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("msg", "用户被禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            model.addAttribute("msg", "认证异常，登录失败！");
            return "login";
        }

    }

    /**
     * 退出
     */
    // @RequestMapping("/logout")
    // public String logout(HttpSession session) {
    //     session.removeAttribute("loginUser");
    //     return "redirect:login"; // 建议重定向，保证删除 Cookie
    // }

    // 未成功的Shiro注销）
    @RequestMapping("/logout")
    public String logout (HttpSession session){
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();//Shiro 注销
        return "main";//最好重定向，保证 Cookie的删除,此处未重定向成功
    }
}
